/**
 * 售后单
 */
Ext.define("PSI.AfterSales.EditForm", {
	extend : "Ext.window.Window",

	config : {
		parentForm : null,
		entity : null
	},

	initComponent : function() {
		var me = this;
		me.__readonly = false;
		var entity = me.getEntity();
		this.adding = entity == null;

		Ext.apply(me, {
			title : entity == null ? "新建售后单" : "编辑售后单",
			modal : true,
			onEsc : Ext.emptyFn,
			maximized : true,
			width : 900,
			height : 600,
			layout : "border",
			tbar : ["-", {
						text : "选择销售订单",
						iconCls : "PSI-button-add",
						handler : me.onSelectSOBill,
						scope : me,
						disabled : me.entity != null
					}, "-", {
						text : "保存",
						iconCls : "PSI-button-ok",
						handler : me.onOK,
						scope : me,
						id : "buttonSave"
					}, "-", {
						text : "取消",
						iconCls : "PSI-button-cancel",
						handler : function() {
							if (me.__readonly) {
								me.close();
								return;
							}

							PSI.MsgBox.confirm("请确认是否取消当前操作？", function() {
										me.close();
									});
						},
						scope : me,
						id : "buttonCancel"
					}],
			defaultFocus : "editBizType",
			items : [{
						region : "center",
						border : 0,
						layout : "fit",
						xtype : "tabpanel",
						id : "tabPanelGrids",
						items : [me.getGoodsGrid(), me.getExGrid()]
					}, {
						region : "north",
						border : 0,
						layout : {
							type : "table",
							columns : 4
						},
						height : 120,
						bodyPadding : 10,
						items : [{
									xtype : "hidden",
									id : "hiddenId",
									name : "id",
									value : entity == null ? null : entity
											.get("id")
								}, {
									id : "editCustomer",
									xtype : "displayfield",
									fieldLabel : "客户",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									colspan : 4,
									width : 800
								}, {
									xtype : "hidden",
									id : "editCustomerId",
									name : "customerId"
								}, {
									id : "editRef",
									fieldLabel : "单号",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "displayfield",
									value : "<span style='color:red'>保存后自动生成</span>"
								}, {
									id : "editBizType",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									fieldLabel : "售后类型",
									beforeLabelTextTpl : PSI.Const.REQUIRED,
									xtype : "combo",
									queryMode : "local",
									editable : false,
									valueField : "id",
									store : Ext.create("Ext.data.ArrayStore", {
												fields : ["id", "text"],
												data : [["0", "退货"],
														["1", "换货"],
														["2", "补发"]]
											}),
									value : "0",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										},
										change : {
											fn : me.onBizTypeChange,
											scope : me
										}
									}
								}, {
									id : "editInWarehouse",
									fieldLabel : "退货入库仓库",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "psi_warehousefield",
									fid : "2037",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editOutWarehouse",
									fieldLabel : "发货出库仓库",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "psi_warehousefield",
									fid : "2037",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editSrvSummary",
									fieldLabel : "问题原因",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "textfield",
									colspan : 2,
									width : 470,
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editBizDT",
									fieldLabel : "业务日期",
									allowBlank : false,
									blankText : "没有输入业务日期",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									beforeLabelTextTpl : PSI.Const.REQUIRED,
									xtype : "datefield",
									format : "Y-m-d",
									value : new Date(),
									name : "bizDT",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editBizUser",
									fieldLabel : "业务员",
									xtype : "psi_userfield",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									allowBlank : false,
									blankText : "没有输入业务员",
									beforeLabelTextTpl : PSI.Const.REQUIRED,
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editPaymentType",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									fieldLabel : "退货记账方式",
									xtype : "combo",
									queryMode : "local",
									editable : false,
									valueField : "id",
									store : Ext.create("Ext.data.ArrayStore", {
												fields : ["id", "text"],
												data : [["0", "记应付账款"],
														["1", "现金付款"],
														["2", "退款转入预收款"]]
											}),
									value : "0",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editRevType",
									labelWidth : 80,
									labelAlign : "right",
									labelSeparator : "",
									fieldLabel : "发货记账方式",
									xtype : "combo",
									queryMode : "local",
									editable : false,
									valueField : "id",
									store : Ext.create("Ext.data.ArrayStore", {
												fields : ["id", "text"],
												data : [["0", "记应收账款"],
														["1", "记现金账"]]
											}),
									value : "0",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}, {
									id : "editSalesMode",
									labelWidth : 120,
									labelAlign : "right",
									labelSeparator : "",
									fieldLabel : "发货销售收入方式",
									colspan : 2,
									width : 470,
									xtype : "combo",
									queryMode : "local",
									editable : false,
									valueField : "id",
									store : Ext.create("Ext.data.ArrayStore", {
												fields : ["id", "text"],
												data : []
											}),
									value : "",
									listeners : {
										specialkey : {
											fn : me.onEditSpecialKey,
											scope : me
										}
									}
								}]
					}],
			listeners : {
				show : {
					fn : me.onWndShow,
					scope : me
				},
				close : {
					fn : me.onWndClose,
					scope : me
				}
			}
		});

		me.callParent(arguments);

		me.__editorList = ["editBizType", "editInWarehouse",
				"editOutWarehouse", "editSrvSummary", "editBizDT",
				"editBizUser", "editPaymentType", "editRevType",
				"editSalesMode"];
	},

	onWindowBeforeUnload : function(e) {
		return (window.event.returnValue = e.returnValue = '确认离开当前页面？');
	},

	onWndClose : function() {
		Ext.get(window).un('beforeunload', this.onWindowBeforeUnload);
	},

	__setBillDataForEdit : function(data) {
		var me = this;

		me.__soBillId = data.soBillId;

		Ext.getCmp("editRef").setValue(data.ref);
		Ext.getCmp("editCustomer").setValue(data.customerName + " 销售订单号: "
				+ data.soBillRef);
		Ext.getCmp("editCustomerId").setValue(data.customerId);
		var editBizType = Ext.getCmp("editBizType");
		editBizType.setValue(data.bizType);
		editBizType.setReadOnly(true);
		var bizType = data.bizType;
		if (bizType == 0 || bizType == 1) {
			Ext.getCmp("editInWarehouse").setIdValue(data.inWarehouseId);
			Ext.getCmp("editInWarehouse").setValue(data.inWarehouseName);
			Ext.getCmp("editPaymentType").setValue(data.paymentType);
		}
		if (bizType == 1 || bizType == 2) {
			Ext.getCmp("editOutWarehouse").setIdValue(data.outWarehouseId);
			Ext.getCmp("editOutWarehouse").setValue(data.outWarehouseName);
			Ext.getCmp("editRevType").setValue(data.receivingType);
			Ext.getCmp("editSalesMode").setValue(data.salesModeId);
		}

		Ext.getCmp("editBizUser").setIdValue(data.bizUserId);
		Ext.getCmp("editBizUser").setValue(data.bizUserName);
		Ext.getCmp("editBizDT").setValue(data.bizDT);
		Ext.getCmp("editSrvSummary").setValue(data.srvSummary);

		var store = me.getGoodsGrid().getStore();
		store.removeAll();
		if (data.rejItems && data.rejItems.length > 0) {
			store.add(data.rejItems);
		}

		var storeEx = me.getExGrid().getStore();
		storeEx.removeAll();
		if (data.exItems && data.exItems.length > 0) {
			storeEx.add(data.exItems);
		} else {
			storeEx.add({
						goodsCount : 1
					});
		}
	},

	onWndShow : function() {
		Ext.get(window).on('beforeunload', this.onWindowBeforeUnload);

		var me = this;
		var el = me.getEl() || Ext.getBody();
		el.mask(PSI.Const.LOADING);
		Ext.Ajax.request({
					url : PSI.Const.BASE_URL + "Home/AfterSales/asBillInfo",
					params : {
						id : Ext.getCmp("hiddenId").getValue()
					},
					method : "POST",
					callback : function(options, success, response) {
						el.unmask();

						if (success) {
							var data = Ext.JSON.decode(response.responseText);

							var editSalesMode = Ext.getCmp("editSalesMode");
							var storeSM = editSalesMode.getStore();
							storeSM.removeAll();
							storeSM.add(data.salesModeList);

							Ext.getCmp("editBizUser")
									.setIdValue(data.bizUserId);
							Ext.getCmp("editBizUser")
									.setValue(data.bizUserName);

							if (data.ref) {
								// 编辑单据
								me.__setBillDataForEdit(data);
							} else {
								// 这是：新建售后单
								// 第一步就是选中销售订单
								me.onSelectSOBill();

								var storeEx = me.getExGrid().getStore();
								storeEx.removeAll();
								storeEx.add({
											goodsCount : 1
										});
							}

							me.setCompStateByBizType();

							if (data.billStatus && data.billStatus != 0) {
								me.setBillReadonly();
							}
						} else {
							PSI.MsgBox.showInfo("网络错误")
						}
					}
				});
	},

	onOK : function() {
		var me = this;

		var bizType = Ext.getCmp("editBizType").getValue();
		if (bizType == 0) {
			// 退货
			var inWarehouseId = Ext.getCmp("editInWarehouse").getIdValue();
			if (!inWarehouseId) {
				PSI.MsgBox.showInfo("没有输入退货入库仓库");
				return;
			}
		} else if (bizType == 1) {
			// 换货
			var inWarehouseId = Ext.getCmp("editInWarehouse").getIdValue();
			if (!inWarehouseId) {
				PSI.MsgBox.showInfo("没有输入退货入库仓库");
				return;
			}
			var outWarehouseId = Ext.getCmp("editOutWarehouse").getIdValue();
			if (!outWarehouseId) {
				PSI.MsgBox.showInfo("没有输入发货出库仓库");
				return;
			}
			var salesModeId = Ext.getCmp("editSalesMode").getValue();
			if (!salesModeId) {
				PSI.MsgBox.showInfo("没有选择发货销售收入方式");
				return;
			}
		} else if (bizType == 2) {
			// 补发
			var outWarehouseId = Ext.getCmp("editOutWarehouse").getIdValue();
			if (!outWarehouseId) {
				PSI.MsgBox.showInfo("没有输入发货出库仓库");
				return;
			}
			var salesModeId = Ext.getCmp("editSalesMode").getValue();
			if (!salesModeId) {
				PSI.MsgBox.showInfo("没有选择发货销售收入方式");
				return;
			}
		}

		Ext.getBody().mask("正在保存中...");
		Ext.Ajax.request({
			url : PSI.Const.BASE_URL + "Home/AfterSales/editASBill",
			method : "POST",
			params : {
				jsonStr : me.getSaveData()
			},
			callback : function(options, success, response) {
				Ext.getBody().unmask();

				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					if (data.success) {
						PSI.MsgBox.showInfo("成功保存数据", function() {
									me.close();
									me.getParentForm().refreshMainGrid(data.id);
								});
					} else {
						PSI.MsgBox.showInfo(data.msg);
					}
				}
			}
		});
	},

	getGoodsGrid : function() {
		var me = this;
		if (me.__goodsGrid) {
			return me.__goodsGrid;
		}

		var modelName = "PSISRBillDetail_EditForm";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "goodsId", "goodsCode", "goodsName",
							"goodsSpec", "unitName", "goodsCount",
							"goodsMoney", "goodsPrice", "rejCount", "rejPrice",
							{
								name : "rejMoney",
								type : "float"
							}, "qcBeginDT", "qcEndDT", "expiration"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__cellEditing = Ext.create("PSI.UX.CellEditing", {
					clicksToEdit : 1,
					listeners : {
						edit : {
							fn : me.cellEditingAfterEdit,
							scope : me
						}
					}
				});

		me.__goodsGrid = Ext.create("Ext.grid.Panel", {
					title : "退货明细",
					viewConfig : {
						enableTextSelection : true
					},
					features : [{
								ftype : "summary"
							}],
					plugins : [me.__cellEditing],
					columnLines : true,
					columns : [Ext.create("Ext.grid.RowNumberer", {
										text : "序号",
										width : 30
									}), {
								header : "商品编码",
								dataIndex : "goodsCode",
								menuDisabled : true,
								draggable : false,
								sortable : false
							}, {
								header : "商品名称",
								dataIndex : "goodsName",
								menuDisabled : true,
								sortable : false,
								draggable : false,
								width : 200
							}, {
								header : "规格型号",
								dataIndex : "goodsSpec",
								menuDisabled : true,
								sortable : false,
								draggable : false,
								width : 200
							}, {
								header : "生产日期",
								dataIndex : "qcBeginDT",
								menuDisabled : true,
								sortable : false,
								width : 80
							}, {
								header : "保质期(天)",
								dataIndex : "expiration",
								menuDisabled : true,
								sortable : false,
								align : "right",
								width : 80
							}, {
								header : "到期日期",
								dataIndex : "qcEndDT",
								menuDisabled : true,
								sortable : false,
								width : 80
							}, {
								header : "退货数量",
								dataIndex : "rejCount",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								width : 100,
								editor : {
									xtype : "numberfield",
									allowDecimals : false,
									hideTrigger : true
								}
							}, {
								header : "单位",
								dataIndex : "unitName",
								menuDisabled : true,
								sortable : false,
								draggable : false,
								width : 60
							}, {
								header : "退货单价",
								dataIndex : "rejPrice",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 100,
								editor : {
									xtype : "numberfield",
									allowDecimals : true,
									hideTrigger : true
								},
								summaryRenderer : function() {
									return "退货金额合计";
								}
							}, {
								header : "退货金额",
								dataIndex : "rejMoney",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 120,
								editor : {
									xtype : "numberfield",
									allowDecimals : true,
									hideTrigger : true
								},
								summaryType : "sum"
							}, {
								header : "销售数量",
								dataIndex : "goodsCount",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								width : 100
							}, {
								header : "销售单价",
								dataIndex : "goodsPrice",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 100
							}, {
								header : "销售金额",
								dataIndex : "goodsMoney",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 120
							}],
					store : store,
					listeners : {
						cellclick : function() {
							return !me.__readonly;
						}
					}
				});

		return me.__goodsGrid;
	},

	cellEditingAfterEdit : function(editor, e) {
		var me = this;
		if (me.__readonly) {
			return;
		}

		var fieldName = e.field;
		var goods = e.record;
		var oldValue = e.originalValue;
		if (fieldName == "rejMoney") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcPrice(goods);
			}
		} else if (fieldName == "rejCount") {
			if (goods.get(fieldName) != oldValue) {
				me.calcMoney(goods);
			}
		} else if (fieldName == "rejPrice") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcMoney(goods);
			}
		}
	},
	calcMoney : function(goods) {
		if (!goods) {
			return;
		}

		var rejCount = goods.get("rejCount");
		if (!rejCount) {
			rejCount = 0;
		}
		var rejPrice = goods.get("rejPrice");
		if (!rejPrice) {
			rejPrice = 0;
		}
		goods.set("rejMoney", rejCount * rejPrice);
	},

	calcPrice : function(goods) {
		if (!goods) {
			return;
		}
		var rejCount = goods.get("rejCount");
		if (rejCount && rejCount != 0) {
			goods.set("rejPrice", goods.get("rejMoney") / rejCount);
		}
	},

	getSaveData : function() {
		var me = this;
		var result = {
			id : Ext.getCmp("hiddenId").getValue(),
			bizType : Ext.getCmp("editBizType").getValue(),
			bizDT : Ext.Date
					.format(Ext.getCmp("editBizDT").getValue(), "Y-m-d"),
			customerId : Ext.getCmp("editCustomerId").getValue(),
			inWarehouseId : Ext.getCmp("editInWarehouse").getIdValue(),
			outWarehouseId : Ext.getCmp("editOutWarehouse").getIdValue(),
			srvSummary : Ext.getCmp("editSrvSummary").getValue(),
			bizUserId : Ext.getCmp("editBizUser").getIdValue(),
			paymentType : Ext.getCmp("editPaymentType").getValue(),
			revType : Ext.getCmp("editRevType").getValue(),
			salesModeId : Ext.getCmp("editSalesMode").getValue(),
			soBillId : me.__soBillId,
			rejItems : [],
			exItems : []
		};

		var store = me.getGoodsGrid().getStore();
		for (var i = 0; i < store.getCount(); i++) {
			var item = store.getAt(i);
			result.rejItems.push({
						id : item.get("id"),
						goodsId : item.get("goodsId"),
						rejCount : item.get("rejCount"),
						rejPrice : item.get("rejPrice"),
						rejMoney : item.get("rejMoney"),
						goodsCount : item.get("goodsCount"),
						goodsPrice : item.get("goodsPrice"),
						goodsMoney : item.get("goodsMoney"),
						qcBeginDT : item.get("qcBeginDT"),
						expiration : item.get("expiration")
					});
		}

		var store = me.getExGrid().getStore();
		for (var i = 0; i < store.getCount(); i++) {
			var item = store.getAt(i);
			result.exItems.push({
						id : item.get("id"),
						goodsId : item.get("goodsId"),
						goodsCount : item.get("goodsCount"),
						goodsPrice : item.get("goodsPrice"),
						goodsMoney : item.get("goodsMoney"),
						qcBeginDT : item.get("qcBeginDT"),
						expiration : item.get("expiration")
					});
		}

		return Ext.JSON.encode(result);
	},

	onSelectSOBill : function() {
		var me = this;
		var form = Ext.create("PSI.AfterSales.SelectSOBillForm", {
					parentForm : me
				});
		form.show();
	},

	getSOBillInfo : function(id) {
		var me = this;
		me.__soBillId = id;
		var el = me.getEl() || Ext.getBody();
		el.mask(PSI.Const.LOADING);
		Ext.Ajax.request({
			url : PSI.Const.BASE_URL + "Home/AfterSales/getSOBillInfoForASBill",
			params : {
				id : id
			},
			method : "POST",
			callback : function(options, success, response) {
				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					Ext.getCmp("editCustomer").setValue(data.customerName
							+ " 销售订单号: " + data.ref);
					Ext.getCmp("editCustomerId").setValue(data.customerId);
					Ext.getCmp("editInWarehouse").setIdValue(data.warehouseId);
					Ext.getCmp("editInWarehouse").setValue(data.warehouseName);

					var store = me.getGoodsGrid().getStore();
					store.removeAll();
					store.add(data.items);
				}

				el.unmask();
			}
		});
	},

	setBillReadonly : function() {
		var me = this;
		me.__readonly = true;
		me.setTitle("查看售后单");
		Ext.getCmp("buttonSave").setDisabled(true);
		Ext.getCmp("buttonCancel").setText("关闭");
		// Ext.getCmp("editBizDT").setReadOnly(true);
		// Ext.getCmp("editWarehouse").setReadOnly(true);
		// Ext.getCmp("editBizUser").setReadOnly(true);
		// Ext.getCmp("editPaymentType").setReadOnly(true);
	},

	// 换货、补发
	getExGrid : function() {
		var me = this;
		if (me.__exGrid) {
			return me.__exGrid;
		}

		var modelName = "PSIASBillExDetail_EditForm";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "goodsId", "goodsCode", "goodsName",
							"goodsSpec", "unitName", "goodsCount",
							"goodsPrice", {
								name : "goodsMoney",
								type : "float"
							}, "qcBeginDT", "expiration"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__cellEditing2 = Ext.create("PSI.UX.CellEditing", {
					clicksToEdit : 1,
					listeners : {
						edit : {
							fn : me.cellEditingAfterEdit2,
							scope : me
						}
					}
				});

		me.__exGrid = Ext.create("Ext.grid.Panel", {
					title : "换货明细/补发明细",
					viewConfig : {
						enableTextSelection : true
					},
					features : [{
								ftype : "summary"
							}],
					plugins : [me.__cellEditing2],
					columnLines : true,
					columns : [Ext.create("Ext.grid.RowNumberer", {
										text : "序号",
										width : 30
									}), {
								header : "商品编码",
								dataIndex : "goodsCode",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								editor : {
									xtype : "psi_goods_with_saleprice_field",
									parentCmp : me,
									hiddenCustomerId : "editCustomerId",
									editWarehouseName : "editOutWarehouse"
								}
							}, {
								header : "商品名称",
								dataIndex : "goodsName",
								menuDisabled : true,
								sortable : false,
								draggable : false,
								width : 200
							}, {
								header : "规格型号",
								dataIndex : "goodsSpec",
								menuDisabled : true,
								sortable : false,
								draggable : false,
								width : 200
							}, {
								header : "生产日期",
								dataIndex : "qcBeginDT",
								menuDisabled : true,
								sortable : false,
								width : 80
							}, {
								header : "保质期(天)",
								dataIndex : "expiration",
								menuDisabled : true,
								sortable : false,
								align : "right",
								width : 80
							}, {
								header : "发货数量",
								dataIndex : "goodsCount",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								width : 100,
								editor : {
									xtype : "numberfield",
									allowDecimals : false,
									hideTrigger : true
								}
							}, {
								header : "单位",
								dataIndex : "unitName",
								menuDisabled : true,
								sortable : false,
								draggable : false,
								width : 60
							}, {
								header : "发货单价",
								dataIndex : "goodsPrice",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 100,
								editor : {
									xtype : "numberfield",
									allowDecimals : true,
									hideTrigger : true
								},
								summaryRenderer : function() {
									return "发货金额合计";
								}
							}, {
								header : "发货金额",
								dataIndex : "goodsMoney",
								menuDisabled : true,
								draggable : false,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 120,
								editor : {
									xtype : "numberfield",
									allowDecimals : true,
									hideTrigger : true
								},
								summaryType : "sum"
							}, {
								header : "",
								id : "columnActionDelete",
								align : "center",
								menuDisabled : true,
								draggable : false,
								width : 40,
								xtype : "actioncolumn",
								items : [{
									icon : PSI.Const.BASE_URL
											+ "Public/Images/icons/delete.png",
									handler : function(grid, row) {
										var store = grid.getStore();
										store.remove(store.getAt(row));
										if (store.getCount() == 0) {
											store.add({});
										}
									},
									scope : me
								}]
							}, {
								header : "",
								id : "columnActionAdd",
								align : "center",
								menuDisabled : true,
								draggable : false,
								width : 40,
								xtype : "actioncolumn",
								items : [{
									icon : PSI.Const.BASE_URL
											+ "Public/Images/icons/add.png",
									handler : function(grid, row) {
										var store = grid.getStore();
										store.insert(row, [{
															goodsCount : 1
														}]);
									},
									scope : me
								}]
							}, {
								header : "",
								id : "columnActionAppend",
								align : "center",
								menuDisabled : true,
								draggable : false,
								width : 40,
								xtype : "actioncolumn",
								items : [{
									icon : PSI.Const.BASE_URL
											+ "Public/Images/icons/add_detail.png",
									handler : function(grid, row) {
										var store = grid.getStore();
										store.insert(row + 1, [{
															goodsCount : 1
														}]);
									},
									scope : me
								}]
							}],
					store : store,
					listeners : {
						cellclick : function() {
							return !me.__readonly;
						}
					}
				});

		return me.__exGrid;
	},

	setCompStateByBizType : function() {
		var me = this;
		var newValue = Ext.getCmp("editBizType").getValue();
		var tabPanel = Ext.getCmp("tabPanelGrids");
		var tab0 = tabPanel.items.getAt(0);
		var tab1 = tabPanel.items.getAt(1);
		if (newValue == 0) {
			// 退货
			Ext.getCmp("editInWarehouse").setDisabled(false);
			Ext.getCmp("editOutWarehouse").setDisabled(true);
			Ext.getCmp("editPaymentType").setDisabled(false);
			Ext.getCmp("editRevType").setDisabled(true);
			Ext.getCmp("editSalesMode").setDisabled(true);

			tab0.setDisabled(false);
			tab1.setDisabled(true);
			tabPanel.setActiveTab(0);
		} else if (newValue == 1) {
			// 换货
			Ext.getCmp("editInWarehouse").setDisabled(false);
			Ext.getCmp("editOutWarehouse").setDisabled(false);
			Ext.getCmp("editPaymentType").setDisabled(false);
			Ext.getCmp("editRevType").setDisabled(false);
			Ext.getCmp("editSalesMode").setDisabled(false);

			tab0.setDisabled(false);
			tab1.setDisabled(false);
			me.getExGrid().setTitle("换货明细");
		} else if (newValue == 2) {
			// 补发
			Ext.getCmp("editInWarehouse").setDisabled(true);
			Ext.getCmp("editOutWarehouse").setDisabled(false);
			Ext.getCmp("editPaymentType").setDisabled(true);
			Ext.getCmp("editRevType").setDisabled(false);
			Ext.getCmp("editSalesMode").setDisabled(false);

			tab0.setDisabled(true);
			tab1.setDisabled(false);
			tabPanel.setActiveTab(1);
			me.getExGrid().setTitle("补发明细");
		}
	},

	onBizTypeChange : function() {
		var me = this;
		me.setCompStateByBizType();
	},

	__setGoodsInfo2 : function(data) {
		var me = this;
		var item = me.getExGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}
		var goods = item[0];

		goods.set("goodsId", data.goodsId);
		goods.set("goodsCode", data.code);
		goods.set("goodsName", data.name);
		goods.set("unitName", data.unitName);
		goods.set("goodsSpec", data.spec);

		goods.set("goodsPrice", data.salePrice);

		goods.set("qcBeginDT", data.qcBeginDT);
		goods.set("expiration", data.expiration);

		me.calcMoney2(goods);
	},

	calcMoney2 : function(goods) {
		if (!goods) {
			return;
		}

		var count = goods.get("goodsCount");
		if (!count) {
			count = 0;
		}
		var price = goods.get("goodsPrice");
		if (!price) {
			price = 0;
		}
		goods.set("goodsMoney", count * price);
	},

	calcPrice2 : function(goods) {
		if (!goods) {
			return;
		}
		var count = goods.get("goodsCount");
		if (count && count != 0) {
			goods.set("goodsPrice", goods.get("goodsMoney") / count);
		}
	},

	cellEditingAfterEdit2 : function(editor, e) {
		var me = this;
		if (me.__readonly) {
			return;
		}

		var fieldName = e.field;
		var goods = e.record;
		var oldValue = e.originalValue;
		if (fieldName == "goodsMoney") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcPrice2(goods);
			}
			var grid = me.getExGrid();
			var store = grid.getStore();
			if (e.rowIdx == store.getCount() - 1) {
				store.add({
							goodsCount : 1
						});
			}
			e.rowIdx += 1;
			grid.getSelectionModel().select(e.rowIdx);
			me.__cellEditing2.startEdit(e.rowIdx, 1);

		} else if (fieldName == "goodsCount") {
			if (goods.get(fieldName) != oldValue) {
				me.calcMoney2(goods);
			}
		} else if (fieldName == "goodsPrice") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcMoney2(goods);
			}
		}
	},

	onEditSpecialKey : function(field, e) {
		if (this.__readonly) {
			return;
		}

		if (e.getKey() === e.ENTER) {
			var me = this;
			var id = field.getId();
			for (var i = 0; i < me.__editorList.length; i++) {
				var editorId = me.__editorList[i];
				if (id === editorId) {
					var next = 1;
					var edit = null;
					while (i + next < me.__editorList.length) {
						edit = Ext.getCmp(me.__editorList[i + next]);
						next++;

						if (!edit.isDisabled()) {
							break;
						}
					}
					if (edit != null) {
						edit.focus();
						edit.setValue(edit.getValue());
					}
				}
			}
		}
	}
});